package main

import (
	"errors"
	"fmt"
	"net/http"
	"reflect"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

// User:IMPI 界面(1张表)
// Impi_ impu(1)
type Impi struct {
	//这里的 json 更改名是指接收前端数据的时候
	ID                     int    //`gorm:"type:int11" json:"id"`
	Identity               string //`gorm:"type:varchar(255)" json:"identity"`
	Name                   string //`gorm:"type:varchar(255)" json:"name"`
	Id_imsu                int    //`gorm:"type:int11" json:"id_imsu"`
	Auth_scheme            int    //`gorm:"type:int11" json:"auth_scheme"`
	Default_auth_scheme    int    //`gorm:"type:int11" json:"default_auth_scheme"`
	Amf_id                 int    //`gorm:"type:int(4)" json:"amf_id"`
	Ip                     string //`gorm:"type:varchar(64)" json:"ip"`
	Line_identifier        string //`gorm:"type:varchar(255)" json:"line_identifier"`
	Zh_uicc_type           int    //`gorm:"type:int11" json:"zh_uicc_type"`
	Zh_key_life_time       int    //`gorm:"type:int11" json:"zh_key_life_time"`
	Zh_default_auth_scheme int    //`gorm:"type:int11" json:"zh_default_auth_scheme"`

	//不需要存数据库，给imsu传参
	Capabilities_set    int
	Preferred_scscf_set int

	Imsu Imsu `gorm:"foreignKey:Id_imsu;references:ID"`
	Amf  Amf  `gorm:"foreignKey:Amf_id;references:Amf_id"`
}

// Impi 关联表 Imsu
type Imsu struct {
	ID                     int    //`gorm:"type:int11" "primaryKey" json:"id"`
	Name                   string //`gorm:"type:varchar(255)" json:"name"`
	ID_capabilities_set    int    //`gorm:"type:int11" json:"id_capabilities_set"
	ID_preferred_scscf_set int    //`gorm:"type:int11" json:"id_preferred_scscf_set"`

	CapabilitiesSet   Capabilities_set    `gorm:"foreignKey:ID_capabilities_set;references:ID"`
	PreferredScscfSet Preferred_scscf_set `gorm:"foreignKey:ID_preferred_scscf_set;references:ID"`
}

// Impi 关联表 Amf
type Amf struct {
	Amf_id    int    //`gorm:"type:int4" json:"id"`
	Amf_value string //`gorm:"type:varchar(5)" json:"name"`
}

// User:IMPU Assionciation 界面(7张表)
// tbl_ims_ impi_impu(1)
type Impi_impu struct {
	//这里的 json 更改名是指接收前端数据的时候
	ID      int //`gorm:"type:int11" json:"id"`
	Id_impi int //`gorm:"type:int11" json:"id_impi"`
	Id_impu int //`gorm:"type:int11" json:"id_impu"`
}

// tbl_ims_ impu(2)
type Impu struct {
	ID               int    //`gorm:"type:int11" "primaryKey" json:"id"`
	Identity         string //`gorm:"type:varchar(255)" json:"identity"`
	Type             int    //`gorm:"type:int(4)" json:"type"`
	Barring          int    //`gorm:"type:int(4)" json:"barring"`
	Id_sp            int    //`gorm:"type:int11" json:"id_sp"`
	Id_implicit_set  int    //`gorm:"type:int11" json:"id_implicit_set"`
	Id_charging_info int    //`gorm:"type:int11" json:"id_charging_info"`
	Wildcard_psi     string //`gorm:"type:varchar(255)" json:"wildcard_psi"`
	Psi_activation   int    //`gorm:"type:int(4)" json:"psi_activation"`
	Can_register     int    //`gorm:"type:int(4)" json:"can_register"`
	Scscf_name       string //`gorm:"type:varchar(255)" json:"scscf_name"`
}

// Impu 关联表 tbl_ims_ charging_info
type Charging_info struct {
	ID      int    //`gorm:"type:int11" "primaryKey" json:"id"`
	Name    string //`gorm:"type:varchar(255)" json:"name"`
	Pri_ecf string //`gorm:"type:varchar(255)" json:"pri_ecf"`
	Sec_ecf string //`gorm:"type:varchar(255)" json:"sec_ecf"`
	Pri_ccf string //`gorm:"type:varchar(255)" json:"pri_ccf"`
	Sec_ccf string //`gorm:"type:varchar(255)" json:"sec_ccf"`

	Impu Impu `gorm:"foreignKey:Id_charging_info;references:ID"`
}

// tbl_ims_ impu_visited_network(3)
type Impu_visited_network struct {
	ID                 int //`gorm:"type:int11" json:"id"`
	ID_impu            int //`gorm:"type:int11" foreignKey:ID_impu;references:ID json:"id_impu"`
	ID_visited_network int //`gorm:"type:int11" foreignKey:ID_visited_network;references:ID json:"id_visited_network"`
}

// tbl_ims_ xcap(4)
type Xcap struct {
	ID                           int    //`gorm:"type:int11" json:"id"`
	Username                     string //`gorm:"type:varchar(255)" json:"username"`
	Oip_active                   int    //`gorm:"type:int(4)" json:"oip_active"`
	Oir_active                   int    //`gorm:"type:int(4)" json:"oir_active"`
	Oir_mode                     int    //`gorm:"type:int(4)" json:"oir_mode"`
	Oir_behaviour                int    //`gorm:"type:int(4)" json:"oir_behaviour"`
	Tip_active                   int    //`gorm:"type:int(4)" json:"tip_active"`
	Tir_active                   int    //`gorm:"type:int(4)" json:"tir_active"`
	Tir_mode                     int    //`gorm:"type:int(4)" json:"tir_mode"`
	Tir_behaviour                int    //`gorm:"type:int(4)" json:"tir_behaviour"`
	Cd_active                    int    //`gorm:"type:int(4)" json:"cd_active"`
	No_reply_timer               int    //`gorm:"type:int11" json:"no_reply_timer"`
	Icb_active                   int    //`gorm:"type:int(4)" json:"icb_active"`
	Icb_rule_deact               int    //`gorm:"type:int(4)" json:"icb_rule_deact"`
	Icb_allow                    int    //`gorm:"type:int(4)" json:"icb_allow"`
	Icb_roam_rule_deact          int    //`gorm:"type:int(4)" json:"icb_roam_rule_deact"`
	Icb_roam_allow               int    //`gorm:"type:int(4)" json:"icb_roam_allow"`
	Ocb_active                   int    //`gorm:"type:int(4)" json:"ocb_active"`
	Ocb_rule_deact               int    //`gorm:"type:int(4)" json:"ocb_rule_deact"`
	Ocb_allow                    int    //`gorm:"type:int(4)" json:"ocb_allow"`
	Ocb_roam_rule_deact          int    //`gorm:"type:int(4)" json:"ocb_roam_rule_deact"`
	Ocb_roam_allow               int    //`gorm:"type:int(4)" json:"ocb_roam_allow"`
	Ocb_international_rule_deact int    //`gorm:"type:int(4)" json:"ocb_international_rule_deact"`
	Ocb_international_allow      int    //`gorm:"type:int(4)" json:"ocb_international_allow"`
	Ocb_exhc_rule_deact          int    //`gorm:"type:int(4)" json:"ocb_exhc_rule_deact"`
	Ocb_exhc_allow               int    //`gorm:"type:int(4)" json:"ocb_exhc_allow"`
	Cw_active                    int    //`gorm:"type:int(4)" json:"cw_active"`

	Impu Impu `gorm:"foreignKey:Identity;references:Username"`
}

// tbl_ims_ repository_data(5)
// Impu Impu `gorm:"foreignKey:Id_impu;references:ID"`
type Repository_data struct {
	ID                 int    //`gorm:"type:int11" json:"id"`
	Sqn                int    //`gorm:"type:int11" json:"sqn"`
	Id_impu            int    //`gorm:"type:int(4)" json:"id_impu"`
	Service_indication string //`gorm:"type:varchar(255)" json:"service_indication"`

	Impu Impu `gorm:"foreignKey:ID;references:Id_impu"`
}

// tbl_ims_ dsai_impu(6)
type Dsai_impu struct {
	ID                 int //`gorm:"type:int11" json:"id"`
	Sqn                int //`gorm:"type:int11" json:"sqn"`
	Id_impu            int //`gorm:"type:int(4)" json:"id_impu"`
	Service_indication int //`gorm:"type:int(4)" json:"service_indication"`
}

// tbl_ims_ calldiversion(7)
type Calldiversion struct {
	ID                   int    //`gorm:"type:int11" json:"id"`
	Username             string //`gorm:"type:varchar(255)" json:"username"`
	Cd_type              int    //`gorm:"type:int(4)" json:"cd_type"`
	Rule_deact           int    //`gorm:"type:int(1)" json:"rule_deact"`
	Media                string //`gorm:"type:varchar(255)" json:"media"`
	Time                 string //`gorm:"type:varchar(20)" json:"time"`
	Target               string //`gorm:"type:varchar(128)" json:"target"`
	No_caller            int    //`gorm:"type:int(1)" json:"no_caller"`
	Re_id_caller         int    //`gorm:"type:int(4)" json:"re_id_caller"`
	Re_ser_uid_caller    int    //`gorm:"type:int(4)" json:"re_ser_uid_caller"`
	No_ser_user          int    //`gorm:"type:int(1)" json:"no_ser_user"`
	No_ser_user_out_call int    //`gorm:"type:int(1)" json:"no_ser_user_out_call"`
	Re_id_target         int    //`gorm:"type:int(4)" json:"re_id_target"`

	Impu Impu `gorm:"foreignKey:Identity;references:Username"`
}

// Network:Visited Network界面(1张表)
// tbl_ims_ visited_network(1)
type Visited_network struct {
	ID       int    //`gorm:"type:int11" "primaryKey" json:"id"`
	Identity string //`gorm:"type:varchar(255)" json:"identity"`
}

// Network:Scscf Capability界面(1张表)
// tbl_ims_ capabilities_set(1)
type Capabilities_set struct {
	ID            int    //`gorm:"type:int11" json:"id"`
	ID_set        int    //`gorm:"type:int11" json:"id_set"`
	Name          string //`gorm:"type:varchar(255)" json:"name"`
	ID_capability int    //`gorm:"type:int11" json:"id_capability"`
	Is_mandatory  int    //`gorm:"type:int11" json:"is_mandatory"`
}

// Capabilities_set 关联表
type Capability struct {
	ID   int    //`gorm:"type:int11" "primaryKey" json:"id"`
	Name string //`gorm:"type:varchar(255)" json:"name"`
}

// Network:Prefered Scscf 界面(1张表)
// tbl_ims_ preferred_scscf_set(1)
type Preferred_scscf_set struct {
	ID         int    //`gorm:"type:int11" json:"id"`
	ID_set     int    //`gorm:"type:int11" json:"id_set"`
	Scscf_name string //`gorm:"type:varchar(255)" json:"scscf_name"`
	Name       string //`gorm:"type:varchar(255)" json:"name"`
	Priority   int    //`gorm:"type:int11" json:"priority"`
}

// Service:Service Profile界面(1张表)
// tbl_ims_ sp(1)
type Sp struct {
	ID              int    //`gorm:"type:int11" json:"id"`
	Name            string //`gorm:"type:varchar(16)" json:"name"`
	Cn_service_auth int    //`gorm:"type:int11" json:"cn_service_auth"`

	Impu Impu `gorm:"foreignKey:Id_sp;references:ID"`
}

// Service:Service Profile Association 界面(4张表)
// tbl_ims_ sp_ifc(1)
type Sp_ifc struct {
	ID       int //`gorm:"type:int11" json:"id"`
	Id_sp    int //`gorm:"type:int11" json:"id_sp"`
	ID_ifc   int //`gorm:"type:int11" json:"id_ifc"`
	Priority int //`gorm:"type:int11" json:"priority"`
}

// tbl_ims_ sp_ifc(2)
type Ifc struct {
	ID                    int    //`gorm:"type:int11" json:"id"`
	Name                  string //`gorm:"type:varchar(16)" json:"name"`
	ID_application_server int    //`gorm:"type:int11" json:"id_application_server"`
	ID_tp                 int    //`gorm:"type:int11" json:"id_tp"`
	Profile_part_ind      int    //`gorm:"type:int11" json:"profile_part_ind"`

	//接收传来数据库字段之外的数据
	Priority int //`gorm:"type:int20" json:"priority"`
	Sp       int //`gorm:json:"sp"`

	Tp                 Tp                 `gorm:"foreignKey:ID_tp;references:ID"`
	Application_server Application_server `gorm:"foreignKey:Name;references:Name"`
}

// tbl_ims_ application_server(3)
type Application_server struct {
	ID                        int    //`gorm:"type:int11" json:"id"`
	Name                      string //`gorm:"type:varchar(255)" gorm:"not null" json:"name"`
	Server_name               string //`gorm:"type:varchar(255)"  json:"server_name"`
	Default_handling          int    //`gorm:"type:int11" json:"default_handling"`
	Service_info              string //`gorm:"type:varchar(255)"  json:"service_info"
	Diameter_address          string //`gorm:"type:varchar(255)"  json:"diameter_address"
	Rep_data_size_limit       int    //`gorm:"type:int11" json:"rep_data_size_limit"`
	Udr                       int    //`gorm:"type:int4" json:"udr"`
	Pur                       int    //`gorm:"type:int4" json:"pur"`
	Snr                       int    //`gorm:"type:int4" json:"snr"`
	Udr_rep_data              int    //`gorm:"type:int4" json:"udr_rep_data"`
	Udr_impu                  int    //`gorm:"type:int4" json:"udr_impu"`
	Udr_ims_user_state        int    //`gorm:"type:int4" json:"udr_ims_user_state"`
	Udr_scscf_name            int    //`gorm:"type:int4" json:"udr_scscf_name"`
	Udr_ifc                   int    //`gorm:"type:int4" json:"udr_ifc"`
	Udr_location              int    //`gorm:"type:int4" json:"udr_location"`
	Udr_user_state            int    //`gorm:"type:int4" json:"udr_user_state"`
	Udr_charging_info         int    //`gorm:"type:int4" json:"udr_charging_info"`
	Udr_msisdn                int    //`gorm:"type:int4" json:"udr_msisdn"`
	Udr_psi_activation        int    //`gorm:"type:int4" json:"udr_psi_activation"`
	Udr_dsai                  int    //`gorm:"type:int4" json:"udr_dsai"`
	Udr_aliases_rep_data      int    //`gorm:"type:int4" json:"udr_aliases_rep_data"`
	Pur_rep_data              int    //`gorm:"type:int4" json:"pur_rep_data"`
	Pur_psi_activation        int    //`gorm:"type:int4" json:"pur_psi_activation"`
	Pur_dsai                  int    //`gorm:"type:int4" json:"pur_dsai"`
	Pur_aliases_rep_data      int    //`gorm:"type:int4" json:"pur_aliases_rep_data"`
	Snr_rep_data              int    //`gorm:"type:int4" json:"snr_rep_data"`
	Snr_impu                  int    //`gorm:"type:int4" json:"snr_impu"`
	Snr_ims_user_state        int    //`gorm:"type:int4" json:"snr_ims_user_state"`
	Snr_scscf_name            int    //`gorm:"type:int4" json:"snr_scscf_name"`
	Snr_ifc                   int    //`gorm:"type:int4" json:"snr_ifc"`
	Snr_psi_activation        int    //`gorm:"type:int4" json:"snr_psi_activation"`
	Snr_dsai                  int    //`gorm:"type:int4" json:"snr_dsai"`
	Snr_aliases_rep_data      int    //`gorm:"type:int4" json:"snr_aliases_rep_data"`
	Include_register_response int    //`gorm:"type:int4" json:"include_register_response"`
	Include_register_request  int    //`gorm:"type:int4" json:"include_register_request"`

	//不需要存数据库，给ifc传参
	ID_ifc int //`gorm:"type:int11" json:"id_ifc"`
}

// tbl_ims_ tp(4)
type Tp struct {
	ID                 int    //`gorm:"type:int11" json:"id"`
	Name               string //`gorm:"type:varchar(255)" json:"name"`
	Condition_type_cnf int    //`gorm:"type:int11" json:"condition_type_cnf"`

	//不需要存数据库，给tp传参
	ID_ifc int //`gorm:"type:int11" json:"id_ifc"`
}

// tbl_ims_ spt(4)
type Spt struct {
	ID                int    //`gorm:"type:int11" json:"id"`
	ID_tp             int    //`gorm:"type:int11" json:"ID_tp"`
	Condition_negated int    //`gorm:"type:int11" json:"condition_negated"`
	Grp               int    //`gorm:"type:int11" json:"grp"`
	Type              int    //`gorm:"type:int11" json:"type"`
	Requesturi        string //`gorm:"type:varchar(255)" json:"requesturi"`
	Method            string //`gorm:"type:varchar(255)" json:"method"`
	Header            string //`gorm:"type:varchar(255)" json:"header"`
	Header_content    string //`gorm:"type:varchar(255)" json:"header_content"`
	Session_case      int    //`gorm:"type:int11" json:"session_case"`
	Sdp_line          string //`gorm:"type:varchar(255)" json:"sdp_line"`
	Sdp_line_content  string //`gorm:"type:varchar(255)" json:"sdp_line_content"`
	Registration_type int    //`gorm:"type:int11" json:"registration_type"`
}

var DB *gorm.DB

func init() {
	// 连接MySQL数据库
	dsn := "root:123456@tcp(10.18.11.64:3306)/lml_dtbase?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "tbl_ims_", //设置表名前缀为 tbl_ims_
			SingularTable: true,       //表名不加s
			NoLowerCase:   false,      //是否关闭小写转换
		},
	})
	if err != nil {
		panic("failed to connect database")
	}
	DB = db
	// 将Impi结构体与数据库中已存在的tbl_ims_impi表建立映射关系
	//User:IMPI
	DB.AutoMigrate(&Impi{})
	//IMPI 关联表
	DB.AutoMigrate(&Imsu{})
	DB.AutoMigrate(&Amf{})
	//User:IMPU  Assionciation
	DB.AutoMigrate(&Impi_impu{})
	DB.AutoMigrate(&Impu{})
	//IMPU 关联表
	DB.AutoMigrate(&Charging_info{})
	//
	DB.AutoMigrate(&Visited_network{})
	DB.AutoMigrate(&Impu_visited_network{})
	DB.AutoMigrate(&Xcap{})
	DB.AutoMigrate(&Repository_data{})
	DB.AutoMigrate(&Dsai_impu{})
	DB.AutoMigrate(&Calldiversion{})
	//Network:Visited Network -> DB.AutoMigrate(&Impu_visited_network{}) 4.15
	//Network:Scscf Capability
	DB.AutoMigrate(&Capabilities_set{})
	//Scscf Capability 关联表
	DB.AutoMigrate(Capability{})
	//Network:Prefered Scscf
	DB.AutoMigrate(&Preferred_scscf_set{})
	//Service:Service Profile
	DB.AutoMigrate(&Sp{})
	//Service:Service Profile Association
	DB.AutoMigrate(&Sp_ifc{})
	DB.AutoMigrate(&Ifc{})
	DB.AutoMigrate(&Application_server{})
	DB.AutoMigrate(&Tp{})
	DB.AutoMigrate(&Spt{})
}

func handle_Add_Request[T any](c *gin.Context, model T) {
	if err := c.ShouldBindJSON(&model); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 使用反射获取模型的类型名称
	typeName := reflect.TypeOf(model).Name()

	// 根据类型名称执行相应的操作
	if typeName == "Impi" /*User IMPI*/ {
		// 将泛型类型参数转换为 interface{}
		modelValue := interface{}(model)
		impi, ok := modelValue.(Impi)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Spt type"})
			return
		}
		// 检查 amf 表中 amf_id 是否与 impi.amf_id 相同
		var amf Amf
		if err := DB.Where("amf_id = ?", impi.Amf_id).First(&amf).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				// 如果不存在,则返回错误
				c.JSON(http.StatusBadRequest, gin.H{"error": "No Tp found with the same ID as impi.Amf_id"})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}
		// 创建 impi 同时 创建 imsu ,一对一关系
		var imsu Imsu
		imsu.Name = impi.Identity
		imsu.ID_capabilities_set = impi.Capabilities_set
		imsu.ID_preferred_scscf_set = impi.Preferred_scscf_set
		if err := DB.Create(&imsu).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.JSON(http.StatusOK, model)
		}

		impi.Id_imsu = imsu.ID
		stmt := fmt.Sprintf("INSERT INTO tbl_ims_impi (id, identity, name, id_imsu, auth_scheme, default_auth_scheme, amf_id, ip, line_identifier, zh_uicc_type, zh_key_life_time, zh_default_auth_scheme) VALUES (%d, '%s', '%s', %d, %d, %d, %d, '%s', '%s', %d, %d, %d)",
			impi.ID, impi.Identity, impi.Name, impi.Id_imsu, impi.Auth_scheme, impi.Default_auth_scheme, impi.Amf_id, impi.Ip, impi.Line_identifier, impi.Zh_uicc_type, impi.Zh_key_life_time, impi.Zh_default_auth_scheme)
		// 执行 Raw SQL 语句
		result := DB.Exec(stmt)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
			return
		}
	} else if typeName == "Impu_visited_network" /*1.1 Allowed Visited Network*/ {
		// 将泛型类型参数转换为 interface{}
		modelValue := interface{}(model)
		impu_visited_network, ok := modelValue.(Impu_visited_network)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Impu_visited_network type"})
			return
		}
		// 检查 impu_visited_network 表中 id_impu 是否与 impu.Id 相同
		var impu Impu
		if err := DB.Where("id = ?", impu_visited_network.ID_impu).First(&impu).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				// 如果不存在,则返回错误
				c.JSON(http.StatusBadRequest, gin.H{"error": "No Impu_visited_network found with the same id_impu as impu.id"})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}
		// 检查 impu_visited_network 表中 id_visited_network 是否与 visited_network.Id 相同
		var visited_network Visited_network
		if err := DB.Where("id = ?", impu_visited_network.ID_visited_network).First(&visited_network).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				// 如果不存在,则返回错误
				c.JSON(http.StatusBadRequest, gin.H{"error": "No Impu_visited_network found with the same ID_visited_network as visited_network.id"})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}
		// 如果存在,则创建 impu_visited_network 记录
		if err := DB.Create(&impu_visited_network).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.JSON(http.StatusOK, model)
		}
	} else if typeName == "Xcap" /*1.2 XCAP*/ {
		// 将泛型类型参数转换为 interface{}
		modelValue := interface{}(model)
		xcap, ok := modelValue.(Xcap)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Xcap type"})
			return
		}
		// 检查 Impu 表中是否存在与 xcap.Username 相同的 Identity
		var impu Impu
		if err := DB.Where("identity = ?", xcap.Username).First(&impu).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				// 如果不存在,则返回错误
				c.JSON(http.StatusBadRequest, gin.H{"error": "No Impu found with the same Identity as Xcap.Username"})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		} else {
			// 如果存在,则创建 Xcap 记录
			if err := DB.Create(&xcap).Error; err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
			c.JSON(http.StatusOK, xcap)
		}
	} else if typeName == "Calldiversion" /*1.3 Call Diversion*/ {
		// 将泛型类型参数转换为 interface{}
		modelValue := interface{}(model)
		cad, ok := modelValue.(Calldiversion)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Calldiversion type"})
			return
		}
		// 检查 Impu 表中是否存在与 Calldiversion.Username 相同的 Identity
		var impu Impu
		if err := DB.Where("identity = ?", cad.Username).First(&impu).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				// 如果不存在,则返回错误
				c.JSON(http.StatusBadRequest, gin.H{"error": "No Impu found with the same Identity as Calldiversion.Username"})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		} else {
			// 如果存在,则创建 Calldiversion 记录
			if err := DB.Create(&cad).Error; err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
			c.JSON(http.StatusOK, cad)
		}
	} else if typeName == "Repository_data" /*1.4 Repository Data*/ {
		// 将泛型类型参数转换为 interface{}
		modelValue := interface{}(model)
		repositoryData, ok := modelValue.(Repository_data)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Repository_data type"})
			return
		}
		// 检查 Impu 表中是否存在与 repositoryData.Id_impu 相同的 ID
		var impu Impu
		if err := DB.Where("id = ?", repositoryData.Id_impu).First(&impu).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				// 如果不存在,则返回错误
				c.JSON(http.StatusBadRequest, gin.H{"error": "No Impu found with the same ID as Repository_data.Id_impu"})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}
		// 如果存在,则创建 Repository_data 记录
		if err := DB.Create(&repositoryData).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, repositoryData)
	} else if typeName == "Ifc" /*1 Initial Filter Criteria*/ {
		//Initial Filter Criteria 传一个sp的id过来说明现在创建的ifc归属于哪个sp
		//会传name(ifc表字段) priority(sp_if表字段)，所以sp_ifc如果没有sp和ifc的对应关系同时满足id_ifc不为空(因为sp可以对应多个ifc)也要创建
		// 将泛型类型参数转换为 interface{}
		modelValue := interface{}(model)
		//1. 获取参数name ，priority ，Profile_part_ind，Sp	 4个
		ifc, ok := modelValue.(Ifc)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Ifc type"})
			return
		}
		//2. 添加ifc表数据
		//因为ifc现在有多余字段，所以直接Create是插入不进去的
		stmt := fmt.Sprintf("INSERT INTO tbl_ims_ifc (id, name, id_application_server, id_tp, profile_part_ind) VALUES (%d, '%s', %d, %d, %d)",
			ifc.ID, ifc.Name, ifc.ID_application_server, ifc.ID_tp, ifc.Profile_part_ind)
		// 执行 Raw SQL 语句
		result := DB.Exec(stmt)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
			return
		}
		//3. 添加sp_ifc表数据，sp和ifc表对应关系
		stmt = fmt.Sprintf("INSERT INTO tbl_ims_sp_ifc (id_tp, id_ifc, priority) VALUES (%d,  %d, %d)",
			ifc.ID_tp, ifc.ID, ifc.Priority)
		// 执行 Raw SQL 语句
		result = DB.Exec(stmt)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
			return
		}
		fmt.Println("handleRequest: error:", result.Error)
	} else if typeName == "Application_server" /*1.1 Application Server*/ {
		//1. 传入所属的 ID_ifc 表明所属 ifc，添加数据到 Application_server 表
		modelValue := interface{}(model)
		//2. 获取参数name ，priority ，Profile_part_ind，Sp	 4个
		application_server, ok := modelValue.(Application_server)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Ifc type"})
			return
		}
		stmt := fmt.Sprintf(`INSERT INTO tbl_ims_application_server (
			name, server_name, default_handling, service_info, diameter_address, rep_data_size_limit,
			udr, pur, snr,
			udr_rep_data, udr_impu, udr_ims_user_state, udr_scscf_name, udr_ifc, udr_location, udr_user_state, udr_charging_info, udr_msisdn, udr_psi_activation, udr_dsai, udr_aliases_rep_data,
			pur_rep_data, pur_psi_activation, pur_dsai, pur_aliases_rep_data,
			snr_rep_data, snr_impu, snr_ims_user_state, snr_scscf_name, snr_ifc, snr_psi_activation, snr_dsai, snr_aliases_rep_data,
			include_register_response, include_register_request
		) VALUES (
			'%s', '%s', %d, '%s', '%s', %d,
			%d, %d, %d,
			%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d,
			%d, %d, %d, %d,
			%d, %d, %d, %d, %d, %d, %d, %d,
			%d, %d
		)`,
			application_server.Name, application_server.Server_name, application_server.Default_handling, application_server.Service_info, application_server.Diameter_address, application_server.Rep_data_size_limit,
			application_server.Udr, application_server.Pur, application_server.Snr,
			application_server.Udr_rep_data, application_server.Udr_impu, application_server.Udr_ims_user_state, application_server.Udr_scscf_name, application_server.Udr_ifc, application_server.Udr_location, application_server.Udr_user_state, application_server.Udr_charging_info, application_server.Udr_msisdn, application_server.Udr_psi_activation, application_server.Udr_dsai, application_server.Udr_aliases_rep_data,
			application_server.Pur_rep_data, application_server.Pur_psi_activation, application_server.Pur_dsai, application_server.Pur_aliases_rep_data,
			application_server.Snr_rep_data, application_server.Snr_impu, application_server.Snr_ims_user_state, application_server.Snr_scscf_name, application_server.Snr_ifc, application_server.Snr_psi_activation, application_server.Snr_dsai, application_server.Snr_aliases_rep_data,
			application_server.Include_register_response, application_server.Include_register_request)
		// 执行 Raw SQL 语句
		result := DB.Exec(stmt)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
			return
		}
		//3. 按照 ifc_id 查找 ifc 表，修改 ifc.id_application_server 字段进行关联
		var ifc Ifc
		if err := DB.Where("id = ?", application_server.ID_ifc).First(&ifc).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				c.JSON(http.StatusNotFound, gin.H{"error": "Ifc not found"})
				return
			}
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 更新 Ifc 记录的 ID_application_server 字段
		ifc.ID_application_server = int(application_server.ID)
		if err := DB.Save(&ifc).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "Application_server and Ifc associated successfully"})
	} else if typeName == "Tp" /*1.2 Trigger Point*/ {
		//1. 传入所属的 ID_ifc 表明所属 ifc，添加数据到 tp 表
		modelValue := interface{}(model)
		//2. 获取参数 name,condition_type 2个
		tp, ok := modelValue.(Tp)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Tp type"})
			return
		}
		// 执行 Raw SQL 语句
		stmt := fmt.Sprintf(`INSERT INTO tbl_ims_tp () VALUES ('%s',  %d)`, tp.Name, tp.Condition_type_cnf)
		result := DB.Exec(stmt)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
			return
		}
		//3. 按照 ifc_id 查找 ifc 表，修改 ifc.id_tp 字段进行关联
		var ifc Ifc
		if err := DB.Where("id = ?", tp.ID_ifc).First(&ifc).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				c.JSON(http.StatusNotFound, gin.H{"error": "Ifc not found"})
				return
			}
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 更新 Ifc 记录的 ID_application_server 字段
		ifc.ID_application_server = int(tp.ID)
		if err := DB.Save(&ifc).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "Application_server and Ifc associated successfully"})
	} else if typeName == "Sp_ifc" {
		// 将泛型类型参数转换为 interface{}
		modelValue := interface{}(model)
		sp_ifc, ok := modelValue.(Sp_ifc)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Sp_ifc type"})
			return
		}
		// 检查 Ifc 表中 id 是否与 sp_ifc.id_ifc 相同
		var ifc Ifc
		if err := DB.Where("id = ?", sp_ifc.ID_ifc).First(&ifc).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				// 如果不存在,则返回错误
				c.JSON(http.StatusBadRequest, gin.H{"error": "No ifc found with the same ID as sp_ifc.ID_ifc"})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}
		// 检查 Sp 表中 id 是否与 sp_ifc.ID_tp 相同
		var sp Sp
		if err := DB.Where("id = ?", sp_ifc.Id_sp).First(&sp).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				// 如果不存在,则返回错误
				c.JSON(http.StatusBadRequest, gin.H{"error": "No sp found with the same ID as sp_ifc.Id_sp"})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}
		// 如果存在,则创建 Ifc 记录
		if err := DB.Create(&sp_ifc).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.JSON(http.StatusOK, model)
		}
	} else if typeName == "Capabilities_set" /*S-CSCF capability*/ {
		// 将泛型类型参数转换为 interface{}
		modelValue := interface{}(model)
		capabilities_set, ok := modelValue.(Capabilities_set)
		if !ok {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Capabilities_set type"})
			return
		}
		// 检查 capability 表中 id 是否与 capabilities_set.id_capabilities 相同
		var application_server Capability
		if err := DB.Where("id = ?", capabilities_set.ID_capability).First(&application_server).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				c.JSON(http.StatusBadRequest, gin.H{"error": "No capability found with the same ID as capabilities_set.ID_capability"})
				return
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				return
			}
		}
		// 如果存在,则创建 capabilities_set 记录
		if err := DB.Create(&capabilities_set).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		} else {
			c.JSON(http.StatusOK, model)
		}
	} else if typeName == "Impu" ||
		typeName == "Preferred_scscf_set" ||
		typeName == "Sp" /*Service:Service Profile*/ ||
		typeName == "Sp_ifc" ||
		typeName == "Visited_network" ||
		typeName == "Spt" {
		fmt.Println("handleRequest: ", typeName, " success!")
		err := DB.Create(&model).Error
		fmt.Println("handleRequest: error:", err)
		c.JSON(http.StatusOK, model)
	} else {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Unsupported type"})
		return
	}
}

func handle_Delete_Request[T any](c *gin.Context, id string, model T) {
	// 使用反射获取模型的类型名称
	typeName := reflect.TypeOf(model).Name()

	// 使用反射获取模型的指针类型
	modelType := reflect.TypeOf(model)
	if modelType.Kind() == reflect.Ptr {
		modelType = modelType.Elem()
	}

	// 创建一个新的模型实例
	modelValue := reflect.New(modelType).Interface()
	// 根据类型名称执行相应的删除操作
	if typeName == "Impi" {
		// 开启事务
		tx := DB.Begin()
		// 在事务中执行删除操作
		// 1. 查找要删除的 Impi 记录
		var impi Impi
		if err := tx.First(&impi, id).Error; err != nil {
			tx.Rollback() // 发生错误,回滚事务
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 2. 删除关联的 Imsu 记录
		if err := tx.Where("id = ?", impi.Id_imsu).Delete(&Imsu{}).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 3. 删除 Impi 记录
		if err := tx.Delete(&impi).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 提交事务
		tx.Commit()
		c.JSON(http.StatusOK, gin.H{"message": "Record deleted successfully"})
	} else if typeName == "Impu" {
		// 开启事务
		tx := DB.Begin()
		// 在事务中执行删除操作
		// 1. 查找要删除的 Impu 记录
		var impu Impu
		if err := tx.First(&impu, id).Error; err != nil {
			tx.Rollback() // 发生错误,回滚事务
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 2.1 删除关联的 Impu_visited_network 记录
		if err := tx.Where("id_impu = ?", impu.ID).Delete(&Impu_visited_network{}).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 2.2 删除关联的 XCAP 记录
		if err := tx.Where("username = ?", impu.Identity).Delete(&Xcap{}).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 2.3 删除关联的 Calldiversion 记录
		if err := tx.Where("username = ?", impu.Identity).Delete(&Calldiversion{}).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 2.4 删除关联的 repository_data 记录
		if err := tx.Where("id_impu = ?", impu.ID).Delete(&Repository_data{}).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 3. 删除 Impi 记录
		if err := tx.Delete(&impu).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 提交事务
		tx.Commit()
		c.JSON(http.StatusOK, gin.H{"message": "Record deleted successfully"})
	} else if typeName == "Xcap" {
		//传进来的是impu的id，要转一下
		// 1. 查找要删除的 Impu 记录
		var impu Impu
		if err := DB.First(&impu, id).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 2. 删除 Xcap 记录
		if err := DB.Where("username = ?", impu.Identity).Delete(&Xcap{}).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "Record deleted successfully"})
	} else if typeName == "Calldiversion" {
		//传进来的是impu的id，要转一下
		// 1. 查找要删除的 Impu 记录
		var impu Impu
		if err := DB.First(&impu, id).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 2. 删除 Calldiversion 记录
		if err := DB.Where("username = ?", impu.Identity).Delete(&Calldiversion{}).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "Record deleted successfully"})
	} else if typeName == "Repository_data" {
		if err := DB.Where("id_impu = ?", id).Delete(&Repository_data{}).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "Record deleted successfully"})
	} else if typeName == "Sp" {
		// 按 sp 的主键 id 进行删除,先在 sp_ifc 表中查找与该 sp 关联的 ifc
		var sp_ifc Sp_ifc
		if err := DB.Where("id_sp = ?", id).First(&sp_ifc).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				// 如果没有找到关联记录,则直接删除 Sp 记录
				if err := DB.Where("id = ?", id).Delete(&Sp{}).Error; err != nil {
					c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
					return
				}
				c.JSON(http.StatusOK, gin.H{"message": "Record deleted successfully"})
				return
			}
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 开启事务 tp sp_ifc
		tx := DB.Begin()
		defer func() {
			if r := recover(); r != nil {
				tx.Rollback()
			}
		}()
		// 查找关联的 Ifc 记录
		var ifc Ifc
		if err := tx.Where("id = ?", sp_ifc.ID_ifc).First(&ifc).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				c.JSON(http.StatusNotFound, gin.H{"error": "Ifc not found"})
			} else {
				c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
				tx.Rollback()
			}
			return
		}
		// 删除关联的 Application_server 记录
		if err := tx.Where("id = ?", ifc.ID_application_server).Delete(&Application_server{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 删除关联的 Spt 记录
		if err := tx.Where("id_tp = ?", ifc.ID_tp).Delete(&Spt{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 删除关联的 Tp 记录
		if err := tx.Where("id = ?", ifc.ID_tp).Delete(&Tp{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 删除 Sp 记录
		if err := tx.Where("id = ?", id).Delete(&Sp{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		// 提交事务
		if err := tx.Commit().Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "Record deleted successfully"})
	} else if typeName == "Visited_network" ||
		typeName == "Capabilities_set" ||
		typeName == "Preferred_scscf_set" ||
		typeName == "Sp_ifc" ||
		typeName == "Impu_visited_network" ||
		typeName == "Ifc" ||
		typeName == "Application_server" {
		result := DB.Where("id = ?", id).Delete(modelValue)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "Record deleted successfully"})
	} else {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Unsupported type"})
		return
	}
}

// 用于分页(通用)
type PaginationParams struct {
	Page     int `form:"page" binding:"required,min=1"`
	PageSize int `form:"page_size" binding:"required,min=1,max=10"`
}

// 用于分页IMPI
type PaginationResult_IMPI struct {
	Data     []Impi `json:"data"`
	Total    int64  `json:"total"`
	Page     int    `json:"page"`
	PageSize int    `json:"page_size"`
}

// 用于分页Visited_network
type PaginationResult_Visited struct {
	Data     []Visited_network `json:"data"`
	Total    int64             `json:"total"`
	Page     int               `json:"page"`
	PageSize int               `json:"page_size"`
}

func main() {
	// 初始化Gin路由
	var r = gin.Default()

	// 通用增加一条记录
	r.POST("/:method", func(c *gin.Context) {
		method := c.Param("method")

		switch method {
		case "impi":
			var impi Impi
			handle_Add_Request(c, impi)
		case "impu":
			var impu Impu
			handle_Add_Request(c, impu)
		case "visited_network":
			var visited_network Visited_network
			handle_Add_Request(c, visited_network)
		case "impu_visited_network":
			// "/impu_visited_network?id_impu=5&id_visited_network=1"
			var impu_visited_network Impu_visited_network
			handle_Add_Request(c, impu_visited_network)
		case "capabilities_set":
			var capabilities_set Capabilities_set
			handle_Add_Request(c, capabilities_set)
		case "preferred_scscf_set":
			var preferred_scscf_set Preferred_scscf_set
			handle_Add_Request(c, preferred_scscf_set)
		case "sp":
			var sp Sp
			handle_Add_Request(c, sp)
		case "sp_ifc":
			var sp_ifc Sp_ifc
			//fmt.Println("sp_ifc Conversion success!")
			handle_Add_Request(c, sp_ifc)
		case "xcap":
			var xcap Xcap
			handle_Add_Request(c, xcap)
		case "calldiversion":
			var calldiversion Calldiversion
			handle_Add_Request(c, calldiversion)
		case "repository_data":
			var repository_data Repository_data
			handle_Add_Request(c, repository_data)
		case "ifc":
			var ifc Ifc
			handle_Add_Request(c, ifc)
		case "application_server":
			var application_server Application_server
			handle_Add_Request(c, application_server)
		case "tp":
			var tp Tp
			handle_Add_Request(c, tp)
		case "spt":
			var spt Spt
			handle_Add_Request(c, spt)

		default:
			c.JSON(http.StatusBadRequest, gin.H{"error": "Unsupported method"})
		}
	})

	//通用删除一条记录
	r.DELETE("/:method/:id", func(c *gin.Context) {
		method := c.Param("method")
		id := c.Param("id")

		switch method {
		case "impi":
			var impi Impi
			handle_Delete_Request(c, id, impi)
		case "impu":
			var impu Impu
			handle_Delete_Request(c, id, impu)
		case "visited_network":
			var visited_network Visited_network
			handle_Delete_Request(c, id, visited_network)
		case "impu_visited_network":
			var impu_visited_network Impu_visited_network
			handle_Delete_Request(c, id, impu_visited_network)
		case "capabilities_set":
			var capabilities_set Capabilities_set
			handle_Delete_Request(c, id, capabilities_set)
		case "preferred_scscf_set":
			var preferred_scscf_set Preferred_scscf_set
			handle_Delete_Request(c, id, preferred_scscf_set)
		case "sp":
			var sp Sp
			handle_Delete_Request(c, id, sp)
		case "xcap":
			var xcap Xcap
			handle_Delete_Request(c, id, xcap)
		case "calldiversion":
			var calldiversion Calldiversion
			handle_Delete_Request(c, id, calldiversion)
		case "repository_data":
			var repository_data Repository_data
			handle_Delete_Request(c, id, repository_data)
		case "ifc":
			var ifc Ifc
			handle_Delete_Request(c, id, ifc)

		default:
			c.JSON(http.StatusBadRequest, gin.H{"error": "Unsupported method"})
		}
	})

	//获取单条记录
	r.GET("/impi/:identity", func(c *gin.Context) {
		var impi Impi
		DB.Where("identity = ?", c.Param("identity")).First(&impi)
		if impi == (Impi{}) {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
			return
		}
		c.JSON(http.StatusOK, impi)
	})
	//关联查询
	//r.GET("/impi/:id", func(c *gin.Context) {
	r.GET("/impi", func(c *gin.Context) {
		var impi Impi
		//result := DB.Preload("Imsu").First(&impi)
		//result := DB.Preload("Imsu").Where("id = ?", c.Param("id")).First(&impi)
		//同级别自动关联了 Imsu 和 Amf
		err := DB.Preload("Imsu.CapabilitiesSet").Preload("Imsu.PreferredScscfSet").First(&impi).Error
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err})
		}
		// result := DB.Preload("Imsu").Where("identity = ?", c.Param("identity")).First(&impi)
		// if result.Error != nil {
		// 	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		// 		c.JSON(http.StatusNotFound, gin.H{"error": "Record not found"})
		// 	} else {
		// 		c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
		// 	}
		// 	return
		// }
		c.JSON(http.StatusOK, impi)
	})
	//关联添加
	// 创建 Impi 记录并关联其他表
	r.POST("/impi2", func(c *gin.Context) {
		impi := Impi{
			ID:       114,
			Identity: "idt5",
			Name:     "xx5",
			Id_imsu:  11,
			Amf_id:   1,
		}
		DB.Create(&impi)
	})

	// 获取所有记录
	// r.GET("/impis", func(c *gin.Context) {
	// 	var impis []Impi
	// 	DB.Find(&impis)
	// 	c.JSON(http.StatusOK, impis)
	// })
	r.GET("/impis", func(c *gin.Context) {
		var impis []Impi
		err := DB.Preload("Imsu.CapabilitiesSet").Preload("Imsu.PreferredScscfSet").Preload("Amf").Find(&impis).Error
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, impis)
	})

	//分页获取记录 IMPI
	//http://ip:port/impis_page?page=5&page_size=2
	r.GET("/impis_page", func(c *gin.Context) {
		var params PaginationParams
		if err := c.ShouldBindQuery(&params); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		offset := (params.Page - 1) * params.PageSize
		limit := params.PageSize

		var impis []Impi
		result := DB.Offset(offset).Limit(limit).Find(&impis)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
			return
		}

		var total int64
		DB.Model(&Impi{}).Count(&total)

		paginationResult := PaginationResult_IMPI{
			Data:     impis,
			Total:    total,
			Page:     params.Page,
			PageSize: params.PageSize,
		}

		c.JSON(http.StatusOK, paginationResult)
	})

	//分页获取记录 Visited Network
	//http://ip:port/visited_page?page=5&page_size=2
	r.GET("/visited_networks_page", func(c *gin.Context) {
		var params PaginationParams
		if err := c.ShouldBindQuery(&params); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		offset := (params.Page - 1) * params.PageSize
		limit := params.PageSize

		var visitedNetworks []Visited_network
		result := DB.Offset(offset).Limit(limit).Find(&visitedNetworks)
		if result.Error != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
			return
		}

		var total int64
		DB.Model(&Visited_network{}).Count(&total)

		paginationResult := PaginationResult_Visited{
			Data:     visitedNetworks,
			Total:    total,
			Page:     params.Page,
			PageSize: params.PageSize,
		}

		c.JSON(http.StatusOK, paginationResult)
	})

	// 更新某条记录
	r.PUT("/impi/:id", func(c *gin.Context) {
		var impi Impi
		if err := DB.Where("id = ?", c.Param("id")).First(&impi).Error; err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
			return
		}

		if err := c.ShouldBindJSON(&impi); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		DB.Save(&impi)
		c.JSON(http.StatusOK, impi)
	})
	// 启动服务器
	r.Run(":8888")
}
